package com.bing.java.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 
 * @author bing
 *
 * 2019年11月9日 上午10:54:12
 * 
 * ReentrantLock锁得同一个对象，释放才能获取锁
 * 
 * 可重入锁
 */
public class ReentrantLockExample {

	private Lock lock = new ReentrantLock();

	public void func() {
		lock.lock();
		try {
			for (int i = 0; i < 10; i++) {
				System.out.print(i + " ");
			}
		} finally {
			lock.unlock(); // 确保释放锁，从而避免发生死锁。
		}
	}

/**
 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 
 * @param args
 * 单对象是一个锁
 */
//	public static void main(String[] args) {
//		ReentrantLockExample lockExample = new ReentrantLockExample();
//		ExecutorService executorService = Executors.newCachedThreadPool();
//		executorService.execute(() -> lockExample.func());
//		executorService.execute(() -> lockExample.func());
//	}
	
	/**
	 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 
	 * @param args
	 * 多对象也是一个锁
	 */
	public static void main(String[] args) {
		ReentrantLockExample lockExample = new ReentrantLockExample();
		ReentrantLockExample lockExample2 = new ReentrantLockExample();
		ExecutorService executorService = Executors.newCachedThreadPool();
		executorService.execute(() -> lockExample.func());
		executorService.execute(() -> lockExample2.func());
	}
}
